package com.myspace.service.impl.post;

import com.myspace.mapper.PostMapper;
import com.myspace.pojo.Post;
import com.myspace.pojo.User;
import com.myspace.service.impl.utils.UserDetailsImpl;
import com.myspace.service.space.post.UpdatePostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UpdatePostServiceImpl implements UpdatePostService {
    @Autowired
    private PostMapper postMapper;

    @Override
    public Map<String, String> updatepost(Integer postId, String content) {
        UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticationToken.getPrincipal();
        User user = loginUser.getUser();

        System.out.println(user.getId());

        Map<String, String> map = new HashMap<>();
        if(content == null) {
            map.put("error_message", "帖子内容不能为空");
            return map;
        }

        if(content.length() > 150) {
            map.put("error_message", "帖子内容不能超过150字");
            return map;
        }

        Post post = postMapper.selectById(postId);
        if(post == null) {
            map.put("error_message", "帖子已经被删除");
            return map;
        }

        Post new_post = new Post(
                postId,
                user.getId(),
                content,
                new Date()
        );

        postMapper.updateById(new_post);
        map.put("error_message", "success");
        return map;
    }
}
